package com.mediocre.eg5topics;

import com.mediocre.constant.Constants;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * exchange模式：主题模式（通配符模式）
 * * (star) can substitute for exactly one word.
 * # (hash) can substitute for zero or more words.
 */
public class EmitLogTopic {

    public static void main(String[] args) throws IOException, TimeoutException {

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        try (Connection connection = connectionFactory.newConnection();
             final Channel channel = connection.createChannel();){
            // channel.exchangeDeclare(EXCHANGE_NAME, "direct");  这个语句也可以
            channel.exchangeDeclare(Constants.EXCHANGE_NAME_TOPIC, BuiltinExchangeType.TOPIC);

            String routingKey = getRouting(args);
            String message = getMessage(args);

            // 此处routingKey参数，和消费者绑定的exchange中感兴趣的路由关键字相同（severity），比如此处可以为 error
            channel.basicPublish(Constants.EXCHANGE_NAME_TOPIC, routingKey, null, message.getBytes(StandardCharsets.UTF_8));
            System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");
        }
    }

    private static String getRouting(String[] strings) {
        if (strings.length < 1) {
            return "info";
        }
        return strings[0];
    }

    private static String getMessage(String[] strings) {
        if (strings.length < 2) {
            return "hello world";
        }
        return joinStrings(strings, " ", 1);
    }

    private static String joinStrings(String[] strings, String delimiter, int startIndex) {
        int length = strings.length;
        if (length == 0 || length <= startIndex) {
            return "";
        }

        StringBuilder words = new StringBuilder(strings[startIndex]);
        for (int i = startIndex + 1; i < length; i++) {
            words.append(delimiter).append(strings[i]);
        }
        return words.toString();
    }

}
